const router = require('koa-router')()

const formidable = require('formidable')
const fs = require('fs');
const url = require('url')
const querystring = require('querystring');
var randomnum =''

//获取当前时间
function getNowFormatDate() {
  let date = new Date(),
    year = date.getFullYear(), //获取完整的年份(4位)
    month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
    strDate = date.getDate(), // 获取当前日(1-31)
    hour = date.getHours(),
    minute = date.getMinutes()
  if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
  if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
  if (hour < 10) hour = `0${hour}` // 如果日是个位数，在前面补0
  if (minute < 10) minute = `0${minute}` // 如果日是个位数，在前面补0
 
  return `${year}-${month}-${strDate}-${hour}-${minute}`
}

//获取数据库投稿列表
router.get('/getDraft',async(ctx,next)=>{

  let sql ='select updraft.*, user_info.nickname,user_info.avatar from updraft left join user_info on updraft.openid = user_info.openid'
  let reslist = await ctx.db.query(sql)
  
  for(i=0;i<reslist.length;i++){
    if(reslist[i].img_name){
      reslist[i].img_name =fs.readFileSync('./public/images/uploadimgs/'+reslist[i].img_name).toString('base64')
    }
  }
  ctx.body={'code':200,'msg':'ok','draftList':reslist}
})

//获取点赞信息
router.get('/discovery/star',async(ctx,next)=>{
  let sql = 'select * from discovery_star'
  let res = await ctx.db.query(sql)
  ctx.body={code:200,data:res}
})

//写入点赞信息
router.post('/discovery/updstar',async(ctx,next)=>{
  let value = ctx.request.body
  let sql = 'insert into discovery_star(draft_id,openid) values(?,?)'
  let res = await ctx.db.query(sql,[value.id,value.openid])
  ctx.body = {code:200,msg:'发送成功'}
})

//删除点赞信息
router.post('/discovery/deStar',async(ctx,next)=>{
  let value = ctx.request.body
  // console.log(value);
  let sql = 'delete from discovery_star where draft_id =? and openid =?'
  let res = await ctx.db.query(sql,[value.id,value.openid])
  ctx.body = {code:200,msg:'请求成功'}
})


//存储投稿标题内容并存储在数据库表中
router.post('/discover-sub',async(ctx,next)=>{
  randomnum = Date.now() 
  let value = ctx.request.body
  if(!value.pote){
    value.pote = 'false'
  }
  console.log(value);
  if(value){
    let sql = 'insert into updraft(openid,union_id,title,content,date,pote,pote_con) values(?,?,?,?,?,?,?)'
    let res = await ctx.db.query(sql,[value.user_id,randomnum,value.title,value.text,getNowFormatDate(),value.pote,value.pote_con])
  }
  ctx.body={'code':200,'msg':'ok'}

})

//存储投稿图片并记录在数据库表（updraft）中
router.post('/uploadImage', async(ctx,next)=>{
  const form = new formidable.IncomingForm()
  form.keepExtensions = true
  form.multiples=true

    form.parse(ctx.req,async (err,fields,files)=>{   //另存上传的文件
      if(files){
        for(key in files){
          let file = files[key]
          const filePath = file.filepath;
          // const fileName = Date.now()+'-' + file.originalFilename;
          const fileName = Math.random().toString(36).slice(-8)+ '-' + file.originalFilename
          const reader = fs.createReadStream(filePath)
          const write= fs.createWriteStream(`./public/images/uploadimgs/${fileName}`)
          reader.pipe(write)

          let fileExtension = fileName.split('.').pop()
          console.log(fileExtension);
          if(!fileExtension){
            fileExtension = 'false'
          }

          let sql = 'update updraft set img_type=?, img_name=? where union_id=?'
          let res = await ctx.db.query(sql,[fileExtension,fileName ,randomnum])
        }
      }else{
        console.log('无文件');
      }
    })


  ctx.body={'code':200,'msg':'ok'}

})

//获取相应评论
router.get('/discovery/getdiscuss',async(ctx,next)=>{
  let reqdata = url.parse(ctx.url).query
  reqdata = querystring.parse(reqdata)
  let id = reqdata.id
  let sql = 'select * from discovery_discuss1 where comment_pr_id =?'
  let res = await ctx.db.query(sql,[id])
  let sql2 = 'select * from discovery_discuss1'
  let res2 = await ctx.db.query(sql2)
  let result = Math.max(...res2.map(x => x.comment_id));  //获取最大的comment_id
  console.log(result);
  ctx.body = {code:200,res:res,lastcomment_id:result}
})

//获取回复评论的评论
router.get('/discovery/getdiscuss2',async(ctx,next)=>{
  let reqdata = url.parse(ctx.url).query
  reqdata = querystring.parse(reqdata)
  let id = reqdata.id
  let sql = 'select * from discovery_discuss2 where comment_pr_id =?'
  let res = await ctx.db.query(sql,[id])
  let sql2 = 'select * from discovery_discuss2'
  let res2 = await ctx.db.query(sql2)
  let result = Math.max(...res2.map(x => x.comment_id));  //获取最大的comment_id
  console.log(result);
  ctx.body = {code:200,res:res,lastcomment_id:result}
})

//将评论存储数据库
router.post('/discovery/upDiscuss',async(ctx,next)=>{
  let value = ctx.request.body
  console.log(value);
  let parent_id = value.parent_id
  let sql = 'insert into discovery_discuss1(comment_pr_id,comment_user_avatar,comment_user_name,comment_user_openid,comment_text,comment_time,reply_id,parent_id,reply_name) values(?,?,?,?,?,?,?,?,?)'
  let sql2 = 'insert into discovery_discuss2(comment_pr_id,comment_user_avatar,comment_user_name,comment_user_openid,comment_text,comment_time,reply_id,parent_id,reply_name) values(?,?,?,?,?,?,?,?,?)'
  if(!parent_id){
    await ctx.db.query(sql,[value.comment_pr_id,value.comment_user_avatar,value.comment_user_name,value.comment_user_openid,value.comment_text,value.comment_time,value.reply_id,value.parent_id,value.reply_name])
  }else{

    await ctx.db.query(sql2,[value.comment_pr_id,value.comment_user_avatar,value.comment_user_name,value.comment_user_openid,value.comment_text,value.comment_time,value.reply_id,value.parent_id,value.reply_name])
  }
  ctx.body={code:200}
})


//获取用户名
router.get('/discovery/getuser',async (ctx,next)=>{
  let reqdata = url.parse(ctx.url).query
  reqdata = querystring.parse(reqdata)
  let openid = reqdata.openid
  let sql = 'select * from user_info where openid = ?'
  let res = await ctx.db.query(sql,[openid])
  ctx.body ={'code':200,'username':res}
})

//获取查询结果
router.get('/discovery/dis-getsearch',async(ctx,next)=>{
  let reqdata = url.parse(ctx.url).query
  reqdata = querystring.parse(reqdata)
  let value = reqdata.vaule
  let sql = `select * from chinesepoetry where name like '%${value}%' or content like '%${value}%' or author like '${value}%' limit 200`
  let res = await ctx.db.query(sql)
  console.log(res);
  ctx.body={code:200,res:res}

})


module.exports = router